<script setup>

import { ref, inject, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { Edit, Plus, Delete, Search, Check } from '@element-plus/icons-vue'

const http = inject('$http'),
	tools = inject('$tools');

let temp = ref({}),
	data = ref({ total: 0, rows: [] }),
	editForm = ref(),
	checkAll = ref(false),
	fetching = ref(false),
	submiting = ref(false),
	showEditForm = ref(false),
	permissionList = ref(null),
	permissionTree = ref();

let query = ref({ page: 1, size: 15, title: '' })

const defaultProps = { children: "children", label: "name" },
	modelTemplate = {
		id: undefined, name: "", display_name: "", permission: [], state: "0",
	};

const resetTemp = function () {
	temp.value = tools.deepCopy(modelTemplate);
	if (showEditForm.value) {
		nextTick(() => permissionTree.value.setCheckedKeys([]));
	}
}

const fetch = async function (inQuery = null) {
	if (inQuery !== null && typeof inQuery === 'object') {
		query.value = Object.assign(query.value, { page: inQuery.page, size: inQuery.size });
	}
	fetching.value = true;
	const res = await http.get("/rbac/role", query.value);
	fetching.value = false;
	if (res.code === 200) {
		data.value = res.data;
	}
	resetTemp();
}

const getPermissionList = async function () {
	const res = await http.get("/rbac/permission");
	if (res.code === 200) {
		permissionList.value = res.data.rows;
	}
}
getPermissionList();

const chooseAll = function () {
	if (checkAll.value) {
		permissionTree.value.setCheckedNodes(permissionList.value);
	} else {
		permissionTree.value.setCheckedNodes([]);
	}
}

const handleCreate = function () {
	resetTemp();
	showEditForm.value = true;
	nextTick(() => {
		editForm.value.clearValidate();
	});
}

const handleEdit = function (row) {
	temp.value = {
		id: row.id, name: row.name, display_name: row.display_name,
		permission: row.permissionIds, state: row.state.toString(),
	};
	if (row.permissionIds) {
		nextTick(() => {
			permissionTree.value.setCheckedKeys(row.permissionIds);
		});
	}
	showEditForm.value = true;
	nextTick(() => {
		editForm.value.clearValidate();
	});
}

const submitForm = function () {
	editForm.value.validate(async (valid) => {
		if (!valid) return;
		temp.value.permission = permissionTree.value.getCheckedKeys();
		console.log(temp.value);
		let res;
		submiting.value = true;
		if (temp.value.id) {
			res = await http.put("/rbac/role", temp.value);
		} else {
			res = await http.post("/rbac/role", temp.value);
		}
		if (res.code === 200) {
			ElMessage({ message: res.message, type: "success" });
			showEditForm.value = false;
			fetch();
		}
		submiting.value = false;
	});
}

const handleDelete = async function (row) {
	console.log(row);
	ElMessageBox.confirm(`确定删除 '${row.display_name}' 角色吗？`, "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "error",
	}).then(async () => {
		let response = await http.delete(`/rbac/role`, { ids: row.id });
		if (response.code === 200) {
			ElMessage({ message: response.message, type: "success" });
			showEditForm.value = false;
			fetch();
		}
	}).catch(() => { });
}

const rules = {
	display_name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
	name: [{ required: true, message: "请输入唯一标识", trigger: "blur" }],
}

fetch();

</script>
<template>
	<h1 class="page-title">角色管理</h1>
	<el-form :inline="true" :model="query" @submit.native.prevent="fetch" class="search-form">
		<el-form-item>
			<el-input v-model="query.title" placeholder="角色名称" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" :icon="Search" :loading="fetching" :disabled="fetching"
				native-type="submit">查询</el-button>
		</el-form-item>
		<el-form-item fixed="right">
			<el-button type="success" :icon="Plus" @click="handleCreate">添加</el-button>
		</el-form-item>
	</el-form>
	<div class="list-box">
		<el-table :data="data.rows" border row-key="id">
			<el-table-column prop="id" label="ID" width="80" />
			<el-table-column prop="display_name" label="角色名称" />
			<el-table-column prop="created_at" label="创建日期" width="180" />
			<el-table-column label="操作" width="300">
				<template #default="scope">
					<el-button type="primary" size="small" :icon="Edit" @click="handleEdit(scope.row)" />
					<el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row)" />
				</template>
			</el-table-column>
		</el-table>
		<Pagination :total="data.total" :page="query.page" :size="query.size" @pagination="fetch" />
	</div>
	<el-dialog v-model="showEditForm" :title="temp.id ? '编辑' : '添加'" :width="'700px'" @close="resetTemp">
		<template #default>
			<el-form ref="editForm" :rules="rules" :model="temp" label-position="left" label-width="80px"
				style="margin: 0 20px">
				<el-form-item label="角色名" prop="display_name">
					<el-input v-model="temp.display_name" placeholder="输入角色名称" />
				</el-form-item>
				<el-form-item label="角色标识" prop="name">
					<el-input v-model="temp.name" placeholder="输入角色标识" />
				</el-form-item>
				<el-form-item label="权限" prop="permission">
					<el-checkbox v-model="checkAll" @change="chooseAll">选中全部</el-checkbox>
					<el-tree :data="permissionList" show-checkbox node-key="id" ref="permissionTree" highlight-current
						:props="defaultProps" />
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-switch v-model="temp.state" active-value="0" inactive-value="1" active-text="正常"
						inactive-text="冻结" />
				</el-form-item>
			</el-form>
		</template>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="showEditForm = false">取消</el-button>
				<el-button type="primary" :disabled="submiting" :loading="submiting" :icon="Check"
					@click="submitForm">保存</el-button>
			</div>
		</template>
	</el-dialog>
</template>